package com.vikutorika.dao.imp;

import com.vikutorika.dao.UserInfoDAO;
import com.vikutorika.dao.BasicDAO;
import com.vikutorika.entity.UserInfo;
import com.vikutorika.util.V_DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.List;

public class UserInfoDAOImp extends BasicDAO<UserInfo> implements UserInfoDAO {
    @Override
    public List<UserInfo> getAll() {
        return null;
    }

    @Override
    public int totalRow() {
        return 0;
    }

    @Override
    public UserInfo getByUID(Integer uid) {
        return null;
    }
    @Override
    public UserInfo getByPhoneNumber(String phone_number) {
        Connection connection = null;
        try {
            connection = V_DBUtils.getConnection();
            String sql = "select * from user_info where phone = ?";
            QueryRunner runner = new QueryRunner();
            UserInfo info = runner.query(connection, sql, new BeanHandler<>(UserInfo.class), phone_number);
            return info;
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            V_DBUtils.close(null, null, connection);
        }
    }
    /**
     *
     * @param userInfo
     * @return 插入成功返回一个对象，失败返回null
     */
    @Override
    public boolean insert(UserInfo userInfo) {
        Connection connection = null;
        try {
            connection = V_DBUtils.getConnection();
            String sql = "insert into user_info(nickname, phone, password_hash) values(?,?,?)";
            QueryRunner qr = new QueryRunner();
            if(getByPhoneNumber(userInfo.getPhone()) != null)
                return false;
            qr.update(connection, sql,userInfo.getNickname(), userInfo.getPhone(), userInfo.getPassword_hash());
            return true;
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            V_DBUtils.close(null, null, connection);
        }
    }

    @Override
    public String getHeadPortraits(Integer uid) {
        Connection connection = null;
        try {
            connection = V_DBUtils.getConnection();
            String sql = "select head_portrait from user_info where uid = ?";
            QueryRunner runner = new QueryRunner();
            String info = runner.query(connection, sql, new ScalarHandler<>(), uid);
            return info;
        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            V_DBUtils.close(connection);
        }
    }
}
